package com.atguigu.juc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class PrintTotal{
    private int number =1;
    Lock lock=new ReentrantLock();
    Condition condition1=lock.newCondition();
    Condition condition2=lock.newCondition();
    Condition condition3=lock.newCondition();
    public void print5(int i) throws InterruptedException {

        lock.lock();
        //判断
        try {
            while (number!=1){
                condition1.await();
            }
            //干活
            for (int j = 1; j <=5 ; j++) {
                System.out.println(Thread.currentThread().getName()+"------   AA"+"这是第"+j+"次"+"-----这是第"+i+"轮");
            }
            //通知
            number=2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }
    public void print10(int i) throws InterruptedException {
        lock.lock();
        //判断
        try {
            while (number!=2){
                condition2.await();
            }
            //干活
            for (int j = 1; j <=10 ; j++) {
                System.out.println(Thread.currentThread().getName()+"------   BB"+"这是第"+j+"次"+"-----这是第"+i+"轮");
            }
            //通知
            number=3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15(int i) throws InterruptedException {
        lock.lock();
        //判断
        try {
            while (number!=3){
                condition3.await();
            }
            //干活
            for (int j = 1; j <=15 ; j++) {
                System.out.println(Thread.currentThread().getName()+"------   CC"+"这是第"+j+"次"+"-----这是第"+i+"轮");
            }
            //通知
            number=1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
/**
 *
 * @Description:
 * 多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
 *
 * AA打印5次，BB打印10次，CC打印15次
 * 接着
 * AA打印5次，BB打印10次，CC打印15次
 * ......来10轮
 *
 */

public class ThreadOrderAccess {
    public static void main(String[] args) {
        PrintTotal printTotal = new PrintTotal();
        new Thread(() -> { for (int i = 1; i <=10 ; i++) {
            try {
                printTotal.print5(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"线程名称1").start();

        new Thread(() -> { for (int i = 1; i <=10 ; i++) {
            try {
                printTotal.print10(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"线程名称2").start();

        new Thread(() -> { for (int i = 1; i <=10 ; i++) {
            try {
                printTotal.print15(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } },"线程名称3").start();
    }

}
